package me.yricky.mayu.ui.file_list

import androidx.compose.ui.graphics.vector.ImageVector
import kotlinx.coroutines.*
import kotlinx.coroutines.flow.*
import java.io.File

/**
 * @author Yricky
 * @date 2022/1/27
 */
class FileBrowseModel(
    var openMethod:((File)->Unit)? = null,
    val icons:((File)->ImageVector?)? = null
) {
    private val coroutineScope:CoroutineScope = CoroutineScope(Dispatchers.Main)
    inner class ViewState(
        val currDir:MutableStateFlow<File> = MutableStateFlow(File(".")),
        val filter:MutableStateFlow<String> = MutableStateFlow(""),
        val files: StateFlow<List<File>> = currDir.combine(filter){ dir,fil ->
            dir.listFiles()?.sorted()?.filter { it.name.contains(fil,true) }?.let{
                listOf(File("${dir.path}/..")).plus(it)
            } ?: emptyList()
        }.flowOn(Dispatchers.IO).stateIn(coroutineScope,SharingStarted.WhileSubscribed(), emptyList()),
    )
    val viewState = ViewState()

    fun setFilter(f:String){
        viewState.filter.value = f
    }

    fun setDir(f:File){
        if(f.canRead() && f.isDirectory){
            viewState.currDir.value = f
            setFilter("")
        }
    }
}